﻿/*
=============================================================================
Author:魏宝辉通过CodeSmithe生成
CreatedTime:2012-11-4
Description:CQuery_FormList.aspx.cs页面代码
=============================================================================	
*/

using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using System.Text;
using FineUI;
using FTchina.SearchQuery;
using FTchina.Library;
using FTchina;
using PWMIS.DataMap.Entity;
using FTchina.Models;
using PWMIS.Common;
using PWMIS.DataProvider.Data;
using FTchina.Logic;
using PWMIS.DataProvider.Adapter;

public partial class CQuery_ShowForm_cs : BasePage
{
    string theId = string.Empty;
    AdoHelper adohelper;//查询用助手
    DBMSType dbtype;//本次查询的数据库类型
    string SqlFrom = string.Empty;//select * From x where x.id=3中的 x 
    string Colums = string.Empty;//select * From x where x.id=3中的 *

    int RowsAllCount = 0;//查询条件个数


    List<Cquery_ColumList> Modlist;//生成查询条件用，提取条件语句也用到




    protected void Page_Load(object sender, EventArgs e)
    {



        theId = RequestHelper.SafeRequest(Request["id"]);

        GetReportInfo(theId);
        if (!IsPostBack)
        {
            LoadData();
        }
    }


    private void LoadData()
    {
        // 关闭按钮的客户端脚本：
        // 1. 首先确认窗体中表单是否被修改（如果已经被修改，则弹出是否关闭的确认对话框）
        // 2. 然后关闭本窗体，回发父窗体
        btnClose.OnClientClick = ActiveWindow.GetConfirmHidePostBackReference();

        if (RequestHelper.SafeRequest(Request["design"]).Length > 0)
        {
            btnSaveContinue.Enabled = false;
        }
    }

    /// <summary>
    /// 获取报表自身的数据，创建表头
    /// </summary>
    /// <param name="ItemID"></param>
    private void GetReportInfo(string ItemID)
    {
        FTchina.Models.CQuery_FormList mCQuery_FormList = FTchina.BLL.CQuery_FormListManager.GetCQuery_FormListById(Convert.ToInt32(ItemID));
        if (mCQuery_FormList != null)
        {
            txbShortView.Text = mCQuery_FormList.ShortView;
        }
        else
        {
            Response.Write("参数错误");
            Response.End();
        }
        SqlFrom = mCQuery_FormList.SqlString;




        SetAdoHelper(mCQuery_FormList);//获取ADOHelper
        GerenQueryControls(mCQuery_FormList);//创建查询条件
    }

    private void GerenQueryControls(CQuery_FormList mCQuery_FormList)
    {
        Cquery_ColumList ccl = new Cquery_ColumList();
        OQLCompare cmp = new OQLCompare(ccl);
        OQLCompare cmpresult = (
            cmp.Comparer(ccl.Guid, OQLCompare.CompareType.Equal, mCQuery_FormList.Guid)
            & cmp.Comparer(ccl.Isinuse, OQLCompare.CompareType.Equal, 1)
            & cmp.Comparer(ccl.IsQuery, OQLCompare.CompareType.Equal, 1)
        );//guid isinuse 过滤条件
        OQL q = new OQL(ccl);
        q.Select().Where(cmpresult).OrderBy(ccl.Paixu, "desc");

        Modlist = EntityQuery<Cquery_ColumList>.QueryList(q, ccl);//放到公用的组合列表里
        RowsAllCount = Modlist.Count;//所有行的查询条件数总和


        for (int i = 0; i < RowsAllCount; i++)
        {

            Cquery_ColumList cclx = (Cquery_ColumList)Modlist[i];
            //LogHelper.Debug(i.ToString() + "*" + j.ToString() + "-1=" + x.ToString());
            if (cclx.ColumID == RequestHelper.GetCookie("OrderColumName"))
            {//关键列不用显示了。
                continue;
            }
            switch (cclx.QueryType)
            {
                case "文本":
                    FineUI.TextBox tbx = new FineUI.TextBox();
                    tbx.ID = cclx.ColumID;
                    tbx.Label = cclx.ColumName.Length == 0 ? cclx.ColumID : cclx.ColumName;
                    tbx.Text = ReportLogic.DefaultValueFormat(cclx.DefaultValue);
                    tbx.Enabled = cclx.IsShow == "1";
                    Form2.Items.Add(tbx);
                    break;
                case "数字":
                    FineUI.NumberBox nbx = new NumberBox();
                    nbx.ID = cclx.ColumID;
                    nbx.Text = ReportLogic.DefaultValueFormat(cclx.DefaultValue);
                    nbx.Label = cclx.ColumName.Length == 0 ? cclx.ColumID : cclx.ColumName;
                    nbx.Enabled = cclx.IsShow == "1";
                    Form2.Items.Add(nbx);
                    break;
                case "日期":
                    DateTime dt;
                    DateTime.TryParse(ReportLogic.DefaultValueFormat(cclx.DefaultValue), out dt);
                    FineUI.DatePicker dp = new DatePicker();
                    dp.ID = cclx.ColumID;
                    dp.Text = dt.ToString();
                    dp.Label = cclx.ColumName.Length == 0 ? cclx.ColumID : cclx.ColumName;
                    dp.Enabled = cclx.IsShow == "1";
                    Form2.Items.Add(dp);
                    break;
                case "下拉框":
                    FineUI.DropDownList ddl = new FineUI.DropDownList();
                    foreach (string keys in cclx.DefaultValue.Split(','))
                    {
                        if (keys.Contains("^"))
                        {
                            ddl.Items.Add(keys.Split('^')[0], keys.Split('^')[1]);
                        }
                        else
                        {
                            ddl.Items.Add(keys, keys);
                        }
                    }
                    ddl.ID = cclx.ColumID;
                    ddl.Label = cclx.ColumName.Length == 0 ? cclx.ColumID : cclx.ColumName;
                    ddl.Enabled = cclx.IsShow == "1";
                    Form2.Items.Add(ddl);
                    break;
                default:
                    break;
            }
        }
    }


    /// <summary>
    /// 设置查询助手
    /// </summary>
    /// <param name="mCQuery_FormList"></param>
    private void SetAdoHelper(CQuery_FormList mCQuery_FormList)
    {
        //初始化数据源模型
        CQuery_ConnString ccs = new CQuery_ConnString();
        ccs.Id = Convert.ToInt64(mCQuery_FormList.ConnID);
        EntityQuery<CQuery_ConnString> query = new EntityQuery<CQuery_ConnString>(ccs);
        query.FillEntity(ccs);

        //获取数据源类型
        dbtype = DBTypeLogic.getDbmsTypeByString(ccs.DbType);


        adohelper = MyDB.GetDBHelper(dbtype, ccs.ConnString);


    }



    /// <summary>
    /// 获取用户更新后的字段名、值集合List
    /// </summary>
    private List<ReportSqlMod> getUserRsmList()
    {
        List<ReportSqlMod> RsmList = new List<ReportSqlMod>();

        for (int i = 0; i < RowsAllCount; i++)
        {

            Cquery_ColumList cclx = (Cquery_ColumList)Modlist[i];
            if (cclx.ColumID == RequestHelper.GetCookie("OrderColumName"))
            {//关键列不用显示了。
                continue;
            }
            switch (cclx.QueryType)
            {
                case "文本":
                    FineUI.TextBox tbx = (FineUI.TextBox)Form2.FindControl(cclx.ColumID);
                    ReportSqlMod rsm = new ReportSqlMod();
                    rsm.ColumID = cclx.ColumID;
                    rsm.ColumValue = tbx.Text;
                    RsmList.Add(rsm);
                    break;
                case "数字":
                    FineUI.NumberBox nbx = (FineUI.NumberBox)Form2.FindControl(cclx.ColumID);
                    ReportSqlMod rsm1 = new ReportSqlMod();
                    rsm1.ColumID = cclx.ColumID;
                    rsm1.ColumValue = nbx.Text;
                    RsmList.Add(rsm1);
                    break;
                case "日期":

                    FineUI.DatePicker dp = (FineUI.DatePicker)Form2.FindControl(cclx.ColumID);
                    ReportSqlMod rsm2 = new ReportSqlMod();
                    rsm2.ColumID = cclx.ColumID;
                    rsm2.ColumValue = dp.Text;
                    RsmList.Add(rsm2);
                    break;
                case "下拉框":
                    FineUI.DropDownList ddl = (FineUI.DropDownList)Form2.FindControl(cclx.ColumID);
                    ReportSqlMod rsm3 = new ReportSqlMod();
                    rsm3.ColumID = cclx.ColumID;
                    rsm3.ColumValue = ddl.SelectedValue;
                    RsmList.Add(rsm3);
                    break;
                default:
                    break;
            }
        }
        return RsmList;
    }





    protected void btnSaveContinue_Click(object sender, EventArgs e)
    {  // 1. 这里放置保存窗体中数据的逻辑
        string[] OrderColumValues = RequestHelper.GetCookie("OrderColumValue").Split(',');
        string OrderColumName = RequestHelper.GetCookie("OrderColumName");
        try
        {
            foreach (string item in OrderColumValues)
            {
                List<ReportSqlMod> RsmList = getUserRsmList();//获取用户填写的字段
                string sqlExec = string.Empty;//存放要执行的SQL语句
                IDataParameter[] para = new IDataParameter[] { };//存放要执行的Para


                ReportSqlMod guid = new ReportSqlMod();//作为存储标识列赋值，每一次遍历都进行赋值
                guid.ColumID = OrderColumName;//字段ID
                guid.ColumValue = item;//传递过来的值

                string SQlTest = "select count(*) from " + SqlFrom + " where " + guid.ColumID + "='" + guid.ColumValue + "'";
                //LogHelper.Debug(adohelper.ExecuteScalar(SQlTest));
                bool exits = Convert.ToInt32(adohelper.ExecuteScalar(SQlTest)) > 0;//看数据是否存在

                if (exits)
                {//已经存在的数据更新
                    ReportLogic.UpdateColums(adohelper, RsmList, SqlFrom, guid, ref sqlExec, ref para);
                }
                else
                {//不存在的数据插入
                    RsmList.Add(guid);//插入数据库需要把标识列一起插入
                    ReportLogic.InsertColums(adohelper, RsmList, SqlFrom, ref sqlExec, ref para);
                }


                AlertLogic.ShowResult(adohelper.ExecuteNonQuery(sqlExec, CommandType.Text, para) != -1);

            }
        }
        catch (Exception er)
        {
            AlertLogic.ShowError(er.Message);
        }
        // 2. 关闭本窗体，然后回发父窗体
        PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
    }








}






